package com.atguigu.sink;

import com.atguigu.bean.WaterSensor;
import com.atguigu.datasource.RandomWatersensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Flink02_sinkMysql {
    public static void main(String[] args) {
        //创建对立MySQL的数据源
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);


        //对数据进行读取处理然后传入到mysql中
        DataStreamSource<WaterSensor> ds = env.addSource(new RandomWatersensor());
        //对数据进行处理然后传入到mysql中
        //以下是老版写法，新版写法到官网去看
        ds.addSink(new RichSinkFunction<WaterSensor>() {

            //创建连接和预编译对象
            private PreparedStatement ps;
            private Connection conn;
            @Override
            public void open(Configuration parameters) throws Exception {

                System.out.println("进入open方法！！！");
                //在这里定义连接对象和预编译对象
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "123321");

                ps = conn.prepareStatement("insert into sensor values(?,?,?)");
            }

            @Override
            public void close() throws Exception {
                //这里对资源进行一个关闭
                conn.close();
                ps.close();
            }

            //invoke方法也是来一条数据就会处理一条数据！
            @Override
            public void invoke(WaterSensor value, Context context) throws Exception {
                //给预编译语句赋值
                System.out.println(value.getId()+"来了，正在进行处理！");
                ps.setString(1, value.getId());
                ps.setLong(2,value.getTs());
                ps.setInt(3,value.getVc());
                ps.execute();

            }
        });

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
